﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using GestionePolveriImporter.Configuration;
using System.Reflection;

namespace GestionePolveriImporter
{
    public class Importer
    {
        private int m_currentIndex = 0;
        private List<KeyValuePair<int, string>> m_mappings = null;
        public string SettingsFilePath { get; set; }
        public GestionePolveriImporter.Configuration.SettingsElmentCollection Settings { get; internal set; }

        public SettingElement Setting 
        {
            get 
            {
                return Settings[m_currentIndex];
            }
        }

        public Importer()
        {
            Load();
        }

        private void Load()
        {
            ImporterSection section = ImporterSection.GetSection("ImporterSection", "Settings");
            if (section != null)
            {
                Settings = section.Settings;
            }
            else
            {
                throw new Exception("Errore nella lettura della sezione di configurazione.");
            }
        }

        private void DoMaps()
        {
            m_mappings = new List<KeyValuePair<int, string>>();

            foreach (MapElement me in Settings[m_currentIndex].Maps)
            {
                m_mappings.Add(new KeyValuePair<int,string>(int.Parse(me.NumberOfColumn), me.PropertyName));
            }
        }

        public int Map(string propertyName)
        {
            KeyValuePair<int, string> element = m_mappings.First(x => x.Value.ToLower() == propertyName.ToLower());

            return element.Key;
        }

        public string Map(int numberOfColumn)
        {
            KeyValuePair<int, string> element = m_mappings.First(x => x.Key == numberOfColumn);
            return element.Value; 
        }

        public IEnumerable<T> Import<T>(int index, Func<int, Importer, IEnumerable<T>> importFunction)
        {
            m_currentIndex = index;

            DoMaps();

            return importFunction(index, this);
        }
    }
}
